<template>
  <div class="dashboard-container">
    <div class="app-container">

      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles" style="width: 100%">
              <el-table-column type="index" :index="indexMethod" label="序号" width="50" />
              <el-table-column prop="name" label="角色名称" width="180" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作" width="300">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="hAssign(scope.row)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                background
                :page-size="pageParams.pagesize"
                layout="prev,pager,next"
                :current-page.sync="curPage"
                :total="total"
                @current-change="hCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 添加编辑弹框 -->
    <el-dialog
      :title=" isShow ? '编辑' : '添加'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="hcancel"
    >
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="showDialog= false">取消</el-button>
          <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 分配权限弹窗 -->
    <el-dialog
      title="分配权限"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogAssign"
    >
      <AssignPermission
        v-if="showDialogAssign"
        :role-id="roleId"
        @close="showDialogAssign=false"
      />
    </el-dialog>
  </div>
</template>
<script>

import { getRoles, deleteRole, addRole, updateRole } from '@/api/settings'
import AssignPermission from './assignPermission.vue'
export default {
  components: {
    AssignPermission
  },
  data() {
    return {
      name: 'settings',
      activeName: 'first',
      isShow: false,
      curPage: 1,
      roles: [],
      roleId: '',
      pageParams: {
        page: 1, // 查询第一页 (当前页数)
        pagesize: 3// 每页两条数据
      },
      total: 0, // 总的数据条数
      showDialog: false, // 显示添加编辑的弹层
      showDialogAssign: false, // 显示分配权限的弹层
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    // 表单中的最大页码
    maxNum() {
      return Math.ceil(this.total / this.pageParams.pagesize)
    },
    isLastPageFulled() {
      return this.total % this.pageParams.pagesize === 0
    },
    // 分页索引接着上一页的索引
    indexMethod() {
      return (this.pageParams.page - 1) * this.pageParams.pagesize + 1
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {

    async  loadRoles() {
      try {
        const res = await getRoles(this.pageParams)
        console.log(res)
        this.roles = res.data.rows
        // console.log('所有用户', this.roles)
        // 页数以及数据条数
        this.roles = res.data.rows
        this.total = res.data.total
        this.curPage = this.pageParams.page
        // console.log('每页显示数据', this.roles)
        // console.log('数据总条数', this.total)
      } catch (err) {
        console.log(err)
      }
    },
    hCurrentChange(curPage) {
      // 更新页码
      this.pageParams.page = curPage
      // 重发请求
      this.loadRoles()
      // console.log('页码', curPage)
    },
    // 删除对话框
    hDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除
    async doDel(id) {
      try {
        const res = await deleteRole(id)
        console.log('需要删除的', res)
        // 删除成功
        this.$message({ type: 'success', message: '删除成功!' })
        // 如果当前页面中只有一条数据，删除之后请求上一页的数据
        if (this.roles.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page === 0) {
            this.pageParams.page = 1
          }
        }
        // 重新请求数据
        this.loadRoles()
      } catch (err) {
        console.log(err)
        this.$message({ type: 'success', message: '删除失败!' })
      }
    },
    // 添加
    async doAdd() {
      try {
        const res = await addRole(this.roleForm)
        console.log(res)

        this.$message.success('添加成功')
        // 添加成功，关闭弹层
        this.showDialog = false
        //   想查看最新添加的数据，要跳到最大页码的下一页
        if (this.isLastPageFulled) {
          this.pageParams.page = this.maxNum + 1
        } else {
          // 想查看最新添加的数据，要跳到最大页码
          this.pageParams.page = this.maxNum
        }
        // 重新加载
        this.loadRoles()
      } catch (err) {
        console.log(err)
      }
    },
    // 编辑
    hEdit(row) {
      // console.log(row)
      this.roleForm = { ...row }
      console.log(this.roleForm)
      // 显示弹层
      this.showDialog = true
      // 编辑状态
      this.isShow = true
    },
    // 编辑保存
    async doEdit() {
      try {
        const res = await updateRole(this.roleForm)
        console.log(res)
        this.$message.success('编辑成功')
        // 更新数据
        this.loadRoles()
        this.showDialog = false
      } catch (err) {
        console.log(err)
      }
    },
    hAdd() {
      // 添加状态
      this.isShow = false
      // 关闭弹层
      this.showDialog = true
    },
    // 校验通过后，执行添加功能
    hSubmit() {
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          this.isShow ? this.doEdit() : this.doAdd()
        }
      })
    },
    // 清空表单
    hcancel() {
      this.showDialog = false
      // 清空表单
      this.roleForm = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    },
    // 显示分配权限弹层
    hAssign(row) {
      this.showDialogAssign = true
      console.log('分配权限', row)
      this.roleId = row.id
    }

  }

}
</script>
